
package com.hlkj.pay.app.merchant.ext.impl.fuyou.handler;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.pay.app.merchant.ext.impl.fuyou.constant.FuYouConstant;
import com.hlkj.pay.app.merchant.ext.impl.fuyou.dto.FuYouConfig;
import com.hlkj.pay.common.CommonResultCode;
import com.hlkj.pay.dto.merchant.MerchantAccessDto;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.infrastructure.model.merchant.*;
import com.hlkj.pay.util.FileUtils;

import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpConfig;
import cn.hutool.extra.ftp.FtpMode;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by Ricky on 2016/11/20.
 */
@Slf4j
@Component
public class FuYouFtpHandler extends FuYouMerchantCommonParamsHandle {

    @Value("${hlkj.upload.directory}")
    public String uploadDirectory;

    /**
     * 营业执照照片
     */
    private String licenseName = "d6a4bcfed5d5c6ac";

    /**
     * 法人身份证正面照片
     */
    private String legalCertFrontName = "b7a8c8cbc9edb7ddd6a4c3f7d5fdc3e6";

    /**
     * 法人身份证明反面
     */
    private String legalCertBackName = "b7a8c8cbc9edb7ddd6a4c3f7b7b4c3e6";

    /**
     * 门脸照片
     */
    private String storeIndoorName = "c3c5c1b3d5d5c6ac";

    /**
     * 门头照片
     */
    private String storeHeaderName = "c3c5cdb7d5d5c6ac";

    /**
     * 对私账户身份证正面（国徽面）照片
     */
    private String certBackName = "b6d4cbbdd5cbbba7c9edb7ddd6a4c3f7d5fdc3e6";

    /**
     * 对私账户身份证反面（人像面）照片
     */
    private String certFrontName = "b6d4cbbdd5cbbba7c9edb7ddd6a4c3f7b1b3c3e6";

    /**
     * 入账银行卡正面照片
     */
    private String settleCardFrontName = "d2f8d0d0bfa8d5fdc3e6";

    /**
     * 入账非法人证明照片
     */
    private String authName = "c8ebd5cbb7c7b7a8c8cbd6a4c3f7";

    /**
     * 开户许可证照片
     */
    private String authLicenseName = "bfaabba7d0edbfc9d6a4";

    /**
     * 收银台图片
     */
    private String storeCashierDeskName = "cad5d2f8cca8cdbcc6ac";
    /**
     * 手持证件照
     */
    private String inHand = "cad6b3d6d6a4bcfed5d5c6ac";

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public CommonResult<String> zipFile(FuYouConfig fuYouConfig, MerchantAccessDto merchantAccessDto) {

        String tempDir = uploadDirectory + File.separator + "fuiou" + File.separator;

        MerchantAccessBusinessDO merchantAccessBusiness = merchantAccessDto.getMerchantAccessBusiness();
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessDto.getMerchantAccessInfo();
        // 商户全称，不能有特殊字符，仅可包含汉字、数字、字母 (需与营业执照一致，如遇提示重复，请在后面加数字1、2...，若为小微商户，请命名为 商户 xxx。)
        MerchantAccessCertInfoDO merchantAccessLegal = merchantAccessDto.getMerchantAccessLegal();
        MerchantAccessLicenseDO merchantAccessLicense = merchantAccessDto.getMerchantAccessLicense();
        MerchantAccessCardDO merchantAccessCard = merchantAccessDto.getMerchantAccessCard();
        MerchantEnum.MERCHANT_TYPE merchantType = MerchantEnum.MERCHANT_TYPE.from(merchantAccessInfo.getType());

        File dir = new File(tempDir + merchantAccessInfo.getSubMchId());
        if (!dir.exists()) {
            Path parentDir = Paths.get(dir.getPath());
            try {
                Files.createDirectories(parentDir);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        String companyType = "A";
        switch (merchantType) {
            case PERSONAL:
                break;
            case COMPANY:
                companyType = companyType(merchantAccessInfo.getType(), merchantAccessLicense);
        }
        if(StringUtils.hasText(merchantAccessCard.getLicenseUrl())){
            log.info("上传开户许可证");
            FileUtils.fileUpload(dir, merchantAccessCard.getLicenseUrl(), authLicenseName);
        }
        List<String> fileUrls = merchantAccessBusiness.getFileUrls();
        if(!CollectionUtils.isEmpty(fileUrls)){
            FileUtils.fileUpload(dir, fileUrls.get(0), inHand);
        }
        MerchantEnum.CARD_TYPE cardType = MerchantEnum.CARD_TYPE.from(merchantAccessCard.getType());
        switch (cardType) {
            case CORPORATE_ACCOUNT:
                // if (!StringUtils.hasText(merchantAccessCard.getLicenseUrl())) {
                //     return CommonResult.error(CommonResultCode.PARAMETER_MISSING.getCode(), "银行卡为对公账户类型,开户许可证 为空");
                // }
                // 开户许可证照片
                // params.put("acnt_type", "1");
                // params.put("acnt_artif_flag", "1");
                // params.put("acnt_nm", merchantAccessLegal.getName());
                break;
            case PRIVATE_CORPORATE_ACCOUNT:
                // params.put("acnt_type", "2");
                // params.put("acnt_artif_flag", "1");
                // params.put("acnt_contact_mobile", merchantAccessCard.getCardPhone());
                // params.put("acnt_nm", merchantAccessLegal.getName());
                if (!StringUtils.hasText(merchantAccessCard.getSettleCardFrontUrl())) {
                    return CommonResult.error(CommonResultCode.PARAMETER_MISSING.getCode(), "银行卡为对私法人账户,银行卡正面 为空");
                }
                FileUtils.fileUpload(dir, merchantAccessCard.getSettleCardFrontUrl(), settleCardFrontName);
                // 入账银行卡正面照片
                break;
            case PRIVATE_NON_CORPORATE_ACCOUNT:
                if (!StringUtils.hasText(merchantAccessCard.getCertBackUrl())) {
                    return CommonResult.error(CommonResultCode.PARAMETER_MISSING.getCode(), "银行卡为对私非法人账户,对私账户身份证反面 为空");
                }
                if (!StringUtils.hasText(merchantAccessCard.getCertFrontUrl())) {
                    return CommonResult.error(CommonResultCode.PARAMETER_MISSING.getCode(), "银行卡为对私非法人账户,对私账户身份证正面 为空");
                }
                if (!StringUtils.hasText(merchantAccessCard.getSettleCardFrontUrl())) {
                    return CommonResult.error(CommonResultCode.PARAMETER_MISSING.getCode(), "银行卡为对私非法人账户,银行卡正面 为空");
                }
                if (!StringUtils.hasText(merchantAccessCard.getAuthUrl())) {
                    return CommonResult.error(CommonResultCode.PARAMETER_MISSING.getCode(), "银行卡为对私非法人账户,授权委托书 为空");
                }
                // 对私账户身份证正面（国徽面）照片
                FileUtils.fileUpload(dir, merchantAccessCard.getCertBackUrl(), certBackName);
                // 对私账户身份证反面（人像面）照片
                FileUtils.fileUpload(dir, merchantAccessCard.getCertFrontUrl(), certFrontName);
                // 入账银行卡正面照片
                FileUtils.fileUpload(dir, merchantAccessCard.getSettleCardFrontUrl(), settleCardFrontName);
                // 入账非法人证明照片
                FileUtils.fileUpload(dir, merchantAccessCard.getAuthUrl(), authName);
                // params.put("acnt_type", "2");
                // params.put("acnt_artif_flag", "0");
                // params.put("acnt_contact_mobile", merchantAccessCard.getCardPhone());
                break;
            default:
        }
        switch (companyType) {
            case "0":
            case "1":
            case "B":
                if (!StringUtils.hasText(merchantAccessLicense.getLicenseUrl())) {
                    return CommonResult.error(CommonResultCode.PARAMETER_MISSING.getCode(), "企业商户,营业执照 为空");
                }
                // 营业执照照片 必填
                FileUtils.fileUpload(dir, merchantAccessLicense.getLicenseUrl(), licenseName);
                break;
        }
        // 法人身份证
        FileUtils.fileUpload(dir, merchantAccessLegal.getCertFrontUrl(), legalCertFrontName);
        FileUtils.fileUpload(dir, merchantAccessLegal.getCertBackUrl(), legalCertBackName);
        // 经营
        FileUtils.fileUpload(dir, merchantAccessBusiness.getStoreIndoorUrl(), storeIndoorName);
        FileUtils.fileUpload(dir, merchantAccessBusiness.getStoreHeaderUrl(), storeHeaderName);
        FileUtils.fileUpload(dir, merchantAccessBusiness.getStoreCashierDeskUrl(), storeCashierDeskName);
        // 要压缩的文件夹路径
        Path folderToZip = Paths.get(dir.getPath());
        // 输出的ZIP文件路径
        Path zipFilePath = Paths.get(dir.getPath() + ".zip");
        try {
            // 调用方法压缩文件夹
            FileUtils.zipFolder(folderToZip, zipFilePath);
            log.info("Folder successfully zipped to:{} ", zipFilePath);
        }
        catch (IOException e) {
            // System.err.println("Error zipping folder: " + e.getMessage());
            log.error("Folder successfully zipped to:{} ", e.getMessage());
            return CommonResult.error(CommonResultCode.SERVICE_ERROR.getCode(), e.getMessage());
        }
        FtpConfig config = new FtpConfig(fuYouConfig.getFtpUrl(), fuYouConfig.getFtpPort(), fuYouConfig.getFtpUserName(), fuYouConfig.getFtpPassWord(), Charset.defaultCharset());
        config.setSoTimeout(30000); // 设置10秒的超时时间
        Ftp ftp = new Ftp(config, FtpMode.Passive);
        try {
            boolean upload = ftp.upload("", zipFilePath.toFile());
            if (!upload) {
                return CommonResult.error(CommonResultCode.PARAMETER_MISSING.getCode(), "上传富友ftp失败 为空");
            }
        }
        catch (Exception e) {
            log.error("Error uploading file: " + e.getMessage());
            return CommonResult.error(CommonResultCode.SERVICE_ERROR.getCode(), e.getMessage());
        }
        finally {
            // 关闭 FTP 连接
            try {
                if (ftp != null) {
                    ftp.close();
                }
            }
            catch (IOException e) {
                log.error("close ftp failed message: ", e, e.getMessage());
            }
            if (folderToZip != null) {
                try {
                    Files.delete(folderToZip);
                }
                catch (IOException e) {
                    log.error("delete folderToZip failed message: ", e, e.getMessage());
                }
            }
            if (zipFilePath != null) {
                try {
                    Files.delete(zipFilePath);
                }
                catch (IOException e) {
                    log.error("delete zipFilePath failed message: ", e, e.getMessage());
                }
            }
        }
        return CommonResult.success();
    }





    public static void main(String[] args) throws UnsupportedEncodingException {
        String response = "%3C%3Fxml+version%3D%221.0%22+encoding%3D%22GBK%22%3F%3E%0A%0A%3Cxml%3E%0A++%3Ctrace_no%3E%3C%2Ftrace_no%3E%0A++%3Cmchnt_name%3E%3C%2Fmchnt_name%3E%0A++%3Cfy_mchnt_cd%3E%3C%2Ffy_mchnt_cd%3E%0A++%3Cret_msg%3E%B2%CE%CA%FD%B8%F1%CA%BD%B4%ED%CE%F3%3Acertif_id%B3%A4%B6%C8%CC%AB%B6%CC%3C%2Fret_msg%3E%0A++%3Cwxapp_mchnt_cd%3E%3C%2Fwxapp_mchnt_cd%3E%0A++%3Cis_effective_acnt%3E%3C%2Fis_effective_acnt%3E%0A++%3Cacnt_upd_no%3E%3C%2Facnt_upd_no%3E%0A++%3Cret_code%3E2001%3C%2Fret_code%3E%0A++%3Cwx_mchnt_cd%3E%3C%2Fwx_mchnt_cd%3E%0A++%3Cauto_buy_cd%3E%3C%2Fauto_buy_cd%3E%0A++%3Cauto_buy_msg%3E%3C%2Fauto_buy_msg%3E%0A++%3Cwechat_mchnt_cd%3E%3C%2Fwechat_mchnt_cd%3E%0A++%3Cacnt_upd_st%3E%3C%2Facnt_upd_st%3E%0A++%3Cacnt_upd_msg%3E%3C%2Facnt_upd_msg%3E%0A++%3Cacnt_upd_ts%3E%3C%2Facnt_upd_ts%3E%0A%3C%2Fxml%3E%0A";
        System.out.println(URLDecoder.decode(response, FuYouConstant.charset));
    }

}
